package com.yvan.periscope.service;

import com.google.common.base.Joiner;
import io.searchbox.client.JestClient;
import com.yvan.es.jest.JestClientFactory;
import com.yvan.es.jest.config.HttpClientConfig;
//import io.searchbox.client.JestClientFactory;
//import io.searchbox.client.config.HttpClientConfig;
import com.yvan.periscope.autoconfig.EsProperties;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableConfigurationProperties(EsProperties.class)
@Slf4j
public class EsFactory {

    @Autowired
    private EsProperties esProperties;

    @Bean
    public JestClient getJestClient() {
        Set<String> servers = new HashSet<>();
        for (String s : esProperties.getAddress()) {
            servers.add(s.trim().toLowerCase());
        }

        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder(servers)
                .connTimeout(esProperties.getConnTimeout())
                .readTimeout(esProperties.getReadTimeout())
                .multiThreaded(true)
                .build());
        log.info("ElasticSearch inited address:" + Joiner.on(",").join(esProperties.getAddress()).toLowerCase());
        return factory.getObject();
    }
}
